//
//  BLCamBarcodeScanLayer.m
//  ITC_iOS
//
//  Created by iBenz on 2018/9/8.
//  Copyright © 2018年 Benz.L. All rights reserved.
//

#import "BLCamBarcodeScanLayer.h"

@interface BLCamBarcodeScanLayer()
@property(nonatomic, strong) CALayer *lineLayer;
@end
@implementation BLCamBarcodeScanLayer

+ (instancetype)scanLayerWithLayer:(AVCaptureVideoPreviewLayer *)avlayer {
    BLCamBarcodeScanLayer *layer = [[self alloc] initWithAVCaptureVideoPreviewLayer:avlayer];
    return layer;
}

- (instancetype)initWithAVCaptureVideoPreviewLayer:(AVCaptureVideoPreviewLayer *)avlayer {
    self = [super init];
    if (self) {
        self.contentsScale = UIScreen.mainScreen.scale;
        self.frame = avlayer.bounds;
        self.contents = (id)[UIImage imageNamed:@"扫描框"].CGImage;
        self.position = (CGPoint){avlayer.bounds.size.width/2.0, avlayer.bounds.size.height/2.0};
        [self addSublayer:self.lineLayer];
        
        [avlayer addSublayer:self];
    }
    return self;
}

- (CALayer *)lineLayer {
    if (!_lineLayer) {
        UIImage *image = [UIImage imageNamed:@"扫描线"];
        _lineLayer = [CALayer layer];
        _lineLayer.contentsScale = UIScreen.mainScreen.scale;
        _lineLayer.bounds = (CGRect){CGPointZero, self.bounds.size.width, image.size.height};
        _lineLayer.contents = (id)image.CGImage;
        _lineLayer.position = (CGPoint){CGRectGetWidth(self.bounds)/2.0, 0};
    }
    return _lineLayer;
}

- (CABasicAnimation *)animation {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position.y"];
    animation.duration = 2;
    animation.fromValue = @(0);
    animation.toValue = @(self.bounds.size.height);
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.repeatCount = HUGE;
//    animation.repeatDuration = 2;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    return animation;
}

- (BOOL)scaning {
    return [self.lineLayer animationForKey:@"scanAnimate"]!=nil;
}

- (void)start {
    if (!self.scaning) {
        [self.lineLayer addAnimation:self.animation forKey:@"scanAnimate"];
    }
}
- (void)stop {
    if (self.scaning) {
        [self.lineLayer removeAnimationForKey:@"scanAnimate"];
    }
}

@end
